package cn.jasonone.hm.netdisc.util;

import cn.jasonone.hm.netdisc.model.dto.HttpResult;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Jason
 * @date 2020-07-23 16:00:44
 */
public class ErrorUtil {
	/**
	 * 解析异常信息
	 * @param br
	 * @return
	 */
	public static Map<String, Map<String,Object>> parseErrors(BindingResult br){
		List<FieldError> errors = br.getFieldErrors();
		HttpResult result = HttpResult.create(400, "非法的参数");
		Map<String, Map<String,Object>> objects = new HashMap<>();
		
		for (FieldError error : errors) {
			Map<String,Object> msg=new HashMap<>();
			String field = error.getField();
			String objectName = error.getObjectName();
			Object value = error.getRejectedValue();
			String message = error.getDefaultMessage();
			if(!objects.containsKey(objectName)){
				objects.put(objectName,new HashMap<>());
			}
			msg.put("value", value);
			msg.put("message", message);
			objects.get(objectName).put(field,msg);
		}
		return objects;
	}
}
